package com.xayq.orap.oauth.token;

import java.security.NoSuchAlgorithmException;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.xayq.orap.model.AccessToken;
import com.xayq.orap.model.ClientDetails;
import com.xayq.orap.model.User;
import com.xayq.orap.utils.CommonUtils;

@Component
public class PasswordTokenHandler extends AbstractOAuthTokenHandler {

    private static final Logger LOG = LoggerFactory.getLogger(PasswordTokenHandler.class);

    /**
     * /oauth/token?client_id=mobile-client&client_secret=mobile&grant_type=password&scope=read,write&username=mobile&password=mobile
     * <p/>
     * Response access_token
     * If exist AccessToken and it is not expired, return it
     * otherwise, return a new AccessToken(include refresh_token)
     * <p/>
     * {"token_type":"Bearer","expires_in":33090,"refresh_token":"976aeaf7df1ee998f98f15acd1de63ea","access_token":"7811aff100eb7dadec132f45f1c01727"}
     */
    @Override
    public void handleAfterValidation() throws OAuthProblemException, OAuthSystemException {

        AccessToken accessToken = oAuthService.retrievePasswordAccessToken(clientDetails(),
                tokenRequest.getScopes(), tokenRequest.getUsername());
        OAuthResponse tokenResponse = createTokenResponse(accessToken, false);

        LOG.debug("'password' response: {}", tokenResponse);
        CommonUtils.writeOAuthJsonResponse(response, tokenResponse);

    }

    //true is invalided
    protected boolean invalidUsernamePassword() {
        String username = tokenRequest.getUsername();
        String password = tokenRequest.getPassword();
        
        User u = userMapper.loadUserByUsername(username);
        try {
			if(CommonUtils.getMD5(password+"{"+username+"}").equals(u.getPassword())){
				return false;
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return true;    
    }

    protected OAuthResponse invalidUsernamePasswordResponse() throws OAuthSystemException {
        return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .setError(OAuthError.TokenResponse.INVALID_GRANT)
                .setErrorDescription("Bad credentials")
                .buildJSONMessage();
    }

	@Override
	protected OAuthResponse validatePlus() throws OAuthSystemException {
		// TODO Auto-generated method stub
		
        
		//validate scope
        Set<String> scopes = getScopes();
        if (!scopes.isEmpty() && excludeScopes(scopes, clientDetails)) {
            return invalidScopeResponse();
        }

        //validate username,password
        if (invalidUsernamePassword()) {
            return invalidUsernamePasswordResponse();
        }

        return null;
	}    
}
